#pragma once

#include <Common/opcode.h>
#include <VM/value.h>

class Chunk
{
	friend class ChunkPrinter;

public:
	u8_t getCode(int offset) const { return code[offset]; }
	void setCode(int offset, u8_t val) { code[offset] = val; }
	int getLine(int offset) const { return lines[offset]; }

	void write(u8_t byte, int line);
	void write(OpCode opcode, int line);

	// add a constant and return its index
	size_t addConstant(Value val);
	const Value &getConstant(int constant) const { return constants[constant]; }

	void disassemble(const char *name);
	int disassembleInstruction(int offset);

	size_t size() const { return code.size(); }

	// Serialize Function
	void serialize(const char *fname = "Chunk.loxc");
	void deserialize(const char *fname);

private:
	std::vector<u8_t> code;		  // 存储字节码
	std::vector<Value> constants; // 常量池
	std::vector<int> lines;		  // 错误信息中的代码行数信息
};